import { defineComponent, ref, inject, watchEffect, computed } from 'vue'
import { NInputNumber, NIcon } from 'naive-ui'
import type { questionSideListState } from '@/types/baseConfig'
import { keyToSlotName } from '@/utils/dyForm'
import questionOption from '@/basic/addEdit/questionsOption'
import type { PropType, Ref } from 'vue'

export default defineComponent({
  props: {
    compData: {
      type: Object as PropType<questionSideListState>,
      default: () => {
        return {}
      }
    }
  },
  emits: ['change'],
  setup(props: any, { emit }) {
    const queryForm = inject('queryForm') as Ref<any> | undefined
    const dySlots = inject('dySlots') as any
    const info = ref<questionSideListState>(questionOption)
    watchEffect(() => {
      info.value = props.compData
    })
    const params = computed(() => {
      const childerProps: any = {}
      if (props.compData?.InputNumberForm) {
        for (const propsKey in props.compData.InputNumberForm) {
          if (props.compData.InputNumberForm[propsKey] !== undefined) {
            childerProps[propsKey] = props.compData.InputNumberForm[propsKey]
          }
        }
      }
      return childerProps
    })

    const slotName = computed(() => {
      return keyToSlotName(info.value.commonForm.labelKey)
    })
    const onChange = () => {
      emit('change', info.value)
    }

    const diySlot = computed(() => {
      const slotInfo: any = {}
      if (dySlots) {
        const dySlotsKeys = Object.keys(dySlots)
        dySlotsKeys.forEach((el: string) => {
          const arr = el.split(':')
          if (arr[0] === slotName.value) {
            const name = arr[1]
            slotInfo[name] = dySlots[el]
          }
        })
      }
      if (!slotInfo['add-icon'] && info.value.InputNumberForm?.addIcon) {
        slotInfo['add-icon'] = () => (
          <NIcon>
            <i class={`esayIcon esayIcon-${info.value.InputNumberForm?.addIcon}`}></i>
          </NIcon>
        )
      }
      if (!slotInfo['minus-icon'] && info.value.InputNumberForm?.minusIcon) {
        slotInfo['minus-icon'] = () => (
          <NIcon>
            <i class={`esayIcon esayIcon-${info.value.InputNumberForm?.minusIcon}`}></i>
          </NIcon>
        )
      }
      return slotInfo
    })

    return () => (
      <div class="text-input w-full">
        {queryForm ? (
          <NInputNumber
            {...params.value}
            v-model:value={queryForm.value[info.value.commonForm.labelKey]}
            update:value={onChange}
            v-slots={diySlot.value}
          />
        ) : (
          <NInputNumber
            {...params.value}
            v-model:value={info.value.commonForm.defaultValue}
            update:value={onChange}
            v-slots={diySlot.value}
          />
        )}
      </div>
    )
  }
})
